<script setup>
import { ref, computed, onMounted } from 'vue'
import { Smile, Calendar, User, Image, Upload } from 'lucide-vue-next'
import OpenAI from 'openai'


const userInfo = ref({
  birthday: '',
  name: ''
})
const userInfoSubmitted = ref(false)
const fortuneSummary = ref('')
const todaysDos = ref([])
const todaysDonts = ref([])
const loading = ref(false)
const error = ref(null)
const incenseAudio = ref(null)

// 电子香状态
const incenseSticks = ref([
  { id: 1, lit: false },
  { id: 2, lit: false },
  { id: 3, lit: false }
])

// 用户上传的图片
const uploadedImage = ref(null)

// 星座中英文映射
const zodiacMap = {
  aries: '白羊座',
  taurus: '金牛座',
  gemini: '双子座',
  cancer: '巨蟹座',
  leo: '狮子座',
  virgo: '处女座',
  libra: '天秤座',
  scorpio: '天蝎座',
  sagittarius: '射手座',
  capricorn: '摩羯座',
  aquarius: '水瓶座',
  pisces: '双鱼座'
}

// 星座计算函数
const calculateZodiac = (birthday) => {
  if (!birthday) return ''

  const date = new Date(birthday)
  const month = date.getMonth() + 1
  const day = date.getDate()

  if ((month === 3 && day >= 21) || (month === 4 && day <= 19)) return 'aries'
  if ((month === 4 && day >= 20) || (month === 5 && day <= 20)) return 'taurus'
  if ((month === 5 && day >= 21) || (month === 6 && day <= 21)) return 'gemini'
  if ((month === 6 && day >= 22) || (month === 7 && day <= 22)) return 'cancer'
  if ((month === 7 && day >= 23) || (month === 8 && day <= 22)) return 'leo'
  if ((month === 8 && day >= 23) || (month === 9 && day <= 22)) return 'virgo'
  if ((month === 9 && day >= 23) || (month === 10 && day <= 23)) return 'libra'
  if ((month === 10 && day >= 24) || (month === 11 && day <= 22)) return 'scorpio'
  if ((month === 11 && day >= 23) || (month === 12 && day <= 21)) return 'sagittarius'
  if ((month === 12 && day >= 22) || (month === 1 && day <= 19)) return 'capricorn'
  if ((month === 1 && day >= 20) || (month === 2 && day <= 18)) return 'aquarius'
  if ((month === 2 && day >= 19) || (month === 3 && day <= 20)) return 'pisces'

  return ''
}

// 计算出的星座
const calculatedZodiac = computed(() => {
  const zodiac = calculateZodiac(userInfo.value.birthday)
  return zodiac ? `${zodiacMap[zodiac]} (${getZodiacDateRange(zodiac)})` : ''
})

// 获取星座日期范围
const getZodiacDateRange = (zodiac) => {
  const ranges = {
    aries: '3.21-4.19',
    taurus: '4.20-5.20',
    gemini: '5.21-6.21',
    cancer: '6.22-7.22',
    leo: '7.23-8.22',
    virgo: '8.23-9.22',
    libra: '9.23-10.23',
    scorpio: '10.24-11.22',
    sagittarius: '11.23-12.21',
    capricorn: '12.22-1.19',
    aquarius: '1.20-2.18',
    pisces: '2.19-3.20'
  }
  return ranges[zodiac] || ''
}

// 当前日期
const currentDate = ref(new Date().toLocaleDateString('zh-CN', {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  weekday: 'long'
}))

// 初始化 OpenAI 客户端
const initOpenAI = () => {
  if (!import.meta.env.VITE_DEEPSEEK_API_KEY) {
    throw new Error('API key is not configured')
  }
  return new OpenAI({
    baseURL: 'https://api.deepseek.com',
    apiKey: import.meta.env.VITE_DEEPSEEK_API_KEY,
    dangerouslyAllowBrowser: true
  })
}

// 提交用户信息
const submitUserInfo = async () => {
  if (!userInfo.value.birthday) {
    error.value = '请填写生日信息'
    return
  }

  loading.value = true
  error.value = null
  userInfoSubmitted.value = true

  try {
    // 尝试API调用
    await fetchFortuneFromAPI()
  } catch (apiError) {
    console.error('API调用失败:', apiError)
    // API失败时使用模拟数据
    useMockData()
    error.value = '运势数据获取失败，已使用模拟数据'
  } finally {
    loading.value = false
  }
}

// 调用AI生成运势
const fetchFortuneFromAPI = async () => {
  try {
    const openai = initOpenAI()
    const zodiac = calculateZodiac(userInfo.value.birthday)

    const prompt = `作为专业占星师，请根据以下用户信息生成今日运势：
用户生日: ${userInfo.value.birthday}
星座: ${zodiacMap[zodiac]}
${userInfo.value.name ? '昵称: ' + userInfo.value.name : ''}

请生成包含以下内容的今日运势：
1. 一段简短的运势概述（50字左右）
2. 今日宜做的3-5件事（用短句描述）
3. 今日忌做的3-5件事（用短句描述）

请用中文回答，并以JSON格式返回：
{
  "summary": "运势概述",
  "dos": ["事项1", "事项2"],
  "donts": ["事项1", "事项2"]
}`

    const completion = await openai.chat.completions.create({
      model: "deepseek-chat",
      messages: [
        { role: "system", content: "你是一位专业的占星师，能够根据用户的生日和星座生成精准的每日运势预测。" },
        { role: "user", content: prompt }
      ],
      temperature: 0.7,
      max_tokens: 500,
      response_format: { type: "json_object" }
    })

    if (completion.choices?.[0]?.message?.content) {
      const result = parseAPIResponse(completion.choices[0].message.content)
      fortuneSummary.value = result.summary || '今日运势平稳，宜把握机会'
      todaysDos.value = result.dos || []
      todaysDonts.value = result.donts || []
    } else {
      throw new Error('API返回数据格式不正确')
    }
  } catch (err) {
    console.error('API调用异常:', err)
    throw err // 抛出错误给上层处理
  }
}

// 解析API响应
const parseAPIResponse = (content) => {
  try {
    return JSON.parse(content)
  } catch (e) {
    console.error('解析API响应失败:', e)
    // 尝试提取可能的JSON部分
    const jsonMatch = content.match(/\{[\s\S]*\}/)
    if (jsonMatch) {
      return JSON.parse(jsonMatch[0])
    }
    throw new Error('无法解析API响应')
  }
}

// 使用模拟数据
const useMockData = () => {
  const zodiac = calculateZodiac(userInfo.value.birthday)
  const zodiacName = zodiac ? zodiacMap[zodiac] : ''

  fortuneSummary.value = `今天是充满活力的一天，${userInfo.value.name || '亲爱的朋友'}！${zodiacName}的你今天运势不错。`
  todaysDos.value = [
    '进行创意工作',
    '结交新朋友',
    '尝试新事物',
    '户外运动'
  ]
  todaysDonts.value = [
    '过度消费',
    '与他人争执',
    '拖延重要决定',
    '熬夜'
  ]
}

// 图片上传处理
const handleImageUpload = (event) => {
  const file = event.target.files[0]
  if (!file) return

  if (!file.type.match('image.*')) {
    error.value = '请上传图片文件'
    return
  }

  const reader = new FileReader()
  reader.onload = (e) => {
    uploadedImage.value = e.target.result
    localStorage.setItem('uploadedIncenseImage', e.target.result)
  }
  reader.readAsDataURL(file)
}

// 加载保存的图片
onMounted(() => {
  const savedImage = localStorage.getItem('uploadedIncenseImage')
  if (savedImage) {
    uploadedImage.value = savedImage
  }
})

// 电子香交互
const lightIncense = (id) => {
  const stick = incenseSticks.value.find(s => s.id === id)
  if (stick) {
    stick.lit = !stick.lit
    if (stick.lit && incenseAudio.value) {
      incenseAudio.value.currentTime = 0
      incenseAudio.value.play().catch(e => console.error('播放音频失败:', e))
    }
  }
}

const resetIncense = () => {
  incenseSticks.value.forEach(stick => {
    stick.lit = false
  })
}

// 重置表单
const resetForm = () => {
  userInfoSubmitted.value = false
  fortuneSummary.value = ''
  todaysDos.value = []
  todaysDonts.value = []
}
</script>

<template>
  <!-- 保持原有的template部分不变 -->
  <div class="fortune-container">
    <h1 class="title">
      <Smile class="icon" /> 每日运势推送
    </h1>
    <p class="date">{{ currentDate }}</p>

    <div v-if="!userInfoSubmitted" class="user-form">
      <div class="form-group">
        <label for="name">
          <User class="icon" /> 您的昵称（可选）
        </label>
        <input
            id="name"
            v-model="userInfo.name"
            type="text"
            placeholder="输入昵称可获得更个性化运势"
        />
      </div>

      <div class="form-group">
        <label for="birthday">
          <Calendar class="icon" /> 您的生日
        </label>
        <input
            id="birthday"
            v-model="userInfo.birthday"
            type="date"
            required
        />
        <div v-if="calculatedZodiac" class="zodiac-display">
          您的星座: {{ calculatedZodiac }}
        </div>
      </div>

      <button
          class="submit-btn"
          @click="submitUserInfo"
          :disabled="loading || !userInfo.birthday"
      >
        {{ loading ? '正在生成...' : '获取今日运势' }}
      </button>

      <p v-if="error" class="error">{{ error }}</p>
    </div>

    <div v-else class="fortune-result">
      <div v-if="loading" class="loading">正在为您生成个性化运势...</div>

      <template v-else>
        <div class="summary">
          <h3>今日运势</h3>
          <p>{{ fortuneSummary }}</p>
        </div>

        <div class="dos-donts">
          <div class="dos">
            <h4>今日宜</h4>
            <ul>
              <li v-for="(item, index) in todaysDos" :key="'do-'+index">
                {{ item }}
              </li>
            </ul>
          </div>

          <div class="donts">
            <h4>今日忌</h4>
            <ul>
              <li v-for="(item, index) in todaysDonts" :key="'dont-'+index">
                {{ item }}
              </li>
            </ul>
          </div>
        </div>

        <button class="reset-btn" @click="resetForm">
          重新生成运势
        </button>
      </template>
    </div>

    <div class="incense-section">
      <h3><Image class="icon" /> 电子上香</h3>

      <div class="upload-section">
        <label class="upload-btn">
          <Upload class="icon" />
          {{ uploadedImage ? '上传你想拜的神' : '上传神像/照片' }}
          <input
              type="file"
              accept="image/*"
              @change="handleImageUpload"
              style="display: none;"
          >
        </label>

        <div v-if="uploadedImage" class="image-preview">
          <img :src="uploadedImage" alt="上传的图片">
        </div>
      </div>

      <div class="incense-area">
        <div class="incense-bowl">
          <div
              v-for="stick in incenseSticks"
              :key="stick.id"
              class="incense-stick"
              :class="{ lit: stick.lit }"
              @click="lightIncense(stick.id)"
          >
            <div class="stick"></div>
            <div class="flame" v-if="stick.lit"></div>
          </div>
        </div>

        <button class="reset-btn" @click="resetIncense">
          重置香火
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 保持原有的样式部分不变 */
.fortune-container {
  max-width: 700px;
  margin: 0 auto;
  padding: 10rem;
  border-radius: 50px;
  position: relative;
  background-image: url("@/assets/temple2.png");
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
  box-shadow: 0 30px 30px rgba(0, 0, 0, 0.3);
}

.content {
  position: relative;
  z-index: 1;
}

.title {
  color: #f4abcf; /* 粉色标题 */
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  font-size: 2rem;
  margin-bottom: 1rem;
}

.user-form, .fortune-result {
  background: linear-gradient(135deg, #ece4b8, #ecba7c); /* 黄橙渐变 */
  border-radius: 15px;
  padding: 3rem;
  margin-bottom: 2rem;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
  border: 2px solid rgba(234, 213, 183, 0.8);
}


.form-group {
  margin-bottom: 1.5rem;
  width: 100%; /* 确保宽度充满容器 */
}

input, select {
  width: calc(100% - 1.5rem); /* 考虑padding后的实际宽度 */
  padding: 1rem;
  margin: 0 auto; /* 水平居中 */
  display: block; /* 使margin-auto生效 */
}

.zodiac-display {
  margin-top: 0.5rem;
  padding: 0.5rem;
  background-color: #aecce6;
  border-radius: 4px;
  font-size: 0.9rem;
}

.submit-btn, .reset-btn, .muyu-btn {
  width: 100%;
  padding: 0.75rem;
  background-color: #a5c38c;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.submit-btn:hover, .reset-btn:hover, .muyu-btn:hover {
  background-color: #a5c38c;
}

.submit-btn:disabled {
  background-color: #6b7e66;
  cursor: not-allowed;
}

.error {
  color: #e74c3c;
  margin-top: 1rem;
  text-align: center;
}

.loading {
  text-align: center;
  color: #666;
  padding: 1rem;
}

.summary {
  margin-bottom: 2rem;
}

.summary h3 {
  color: #7a91ec;
  margin-bottom: 0.5rem;
}

.summary p {
  color: #ffffff;
  line-height: 1.6;
}

.dos-donts {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.dos, .donts {
  padding: 1rem;
  border-radius: 6px;
}

.dos {
  background-color: rgb(117, 182, 136);
  border: 1px solid rgba(46, 204, 113, 0.3);
}

.donts {
  background-color: rgba(205, 127, 120, 0.96);
  border: 1px solid rgba(231, 76, 60, 0.3);
}

.dos h4 {
  color: #a7e6c2;
  margin-bottom: 0.5rem;
}

.donts h4 {
  color: #e4afa8;
  margin-bottom: 0.5rem;
}

ul {
  padding-left: 1.25rem;
  margin: 0;
}

li {
  margin-bottom: 0.5rem;
  color: #edeaea;
}

.incense-section {
  background-color: #ecc7b0;
  padding: 1.5rem;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-top: 2rem;
}

.upload-section {
  margin: 1rem 0;
}

.upload-btn {
  display: inline-flex;
  align-items: center;
  padding: 0.75rem 1.5rem;
  background-color: #a5c38c;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s;
  margin: 0 auto; /* 新增：使按钮本身居中 */
  display: block; /* 新增：使margin-auto生效 */
  width: fit-content; /* 新增：让按钮宽度适应内容 */
}

.upload-btn:hover {
  background-color: #e0e0e0;
}

.image-preview {
  margin-top: 1rem;
  display: flex; /* 新增：启用flex布局 */
  justify-content: center; /* 新增：水平居中 */
  align-items: center; /* 新增：垂直居中 */
  flex-direction: column; /* 新增：纵向排列 */
}

.image-preview img {
  max-width: 100%;
  max-height: 200px;
  border-radius: 6px;
  border: 1px solid #ddd;
  display: block; /* 新增：消除图片底部间隙 */
  margin: 0 auto; /* 新增：水平居中（双重保障） */
}

/* 如果需要限制预览区域大小 */
.image-preview-container {
  width: 100%;
  text-align: center; /* 传统居中方式作为备用 */
}

.incense-area {
  margin-top: 1.5rem;
  text-align: center;
}

.incense-bowl {
  position: relative;
  height: 200px;
  background-color: #f5f5f5;
  border-radius: 8px;
  margin-bottom: 1rem;
  display: flex;
  justify-content: space-around;
  align-items: flex-end;
  padding-bottom: 20px;
}

.incense-stick {
  position: relative;
  width: 30px;
  height: 120px;
  cursor: pointer;
}

.stick {
  width: 4px;
  height: 100px;
  background-color: #8B4513;
  margin: 0 auto;
  border-radius: 2px;
}

.flame {
  position: absolute;
  top: -15px;
  left: 50%;
  transform: translateX(-50%);
  width: 12px;
  height: 20px;
  background: linear-gradient(to top, #eabc97, #e3daa0);
  border-radius: 50% 50% 20% 20%;
  box-shadow: 0 0 10px #f6dc99, 0 0 20px #ecba7c;
  animation: flicker 1s infinite alternate;
}

.incense-stick.lit .stick {
  background-color: #A0522D;
}


@keyframes flicker {
  0% { opacity: 0.8; transform: translateX(-50%) scale(0.95); }
  100% { opacity: 1; transform: translateX(-50%) scale(1.05); }
}
</style>